<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 地区模型
 * 
 * @desc    地区管理
 * @version 1.0.0 
 * @author  Jason
 * @date	2017年5月2日 下午3:19:32
 * 
 * @version 2.0.0
 * @desc	树型结构数据方法放到单独的 trait 里面。
 * @author	Jason
 * @date	2017年7月3日 下午2:08:05
 */
class Mod_area extends MY_Model
{
	use models\common\MultipleLanguage;
	use models\common\TreeStructure; // 注意 before_treeStructure_create_data_handler
	
	protected $table_mapper = [
			'master' => 'area',
	];
	
	protected $allowed_fields = [
			'master' => ['name', 'parent_id', 'short_name', 
				'latitude', 'longitude', 'level', 'position', 'sort_order'],
	];
	
	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		
		$this->multi_language_handler();
	}
	
	/**
	 * 插入前处理器
	 *
	 * @param array  $data
	 * @param string $mapping	表映射
	 *
	 * @return array
	 */
	public function before_create_data_handler($data, $mapping = 'master')
	{
		$data['short_name'] = empty($data['short_name']) ? $data['name'] : $data['short_name'];
		$data = $this->before_treeStructure_create_data_handler($data, $mapping);
		
		return $data;
	}
	
	/**
	 * 删除前处理器
	 *
	 * @param array  $data
	 * @param string $mapping	表映射
	 *
	 * @return array
	 * TODO FIXME 可能需要优化返回值的
	 */
	public function before_delete_data_handler($id, $mapping = 'master')
	{
		$conditions = [
				['where', "parent_id='$id'"],
		];
		$subCount = $this->select_count_by_conditions($conditions, $mapping);
		if ($subCount > 0) {
			//return false;
			return 'common_msg_still_has_children';
		}
		
		return true;
	}
	
	/**
	 * 获得地址字符串
	 *
	 * @param  int  $id  地区ID
	 *
	 * @return string
	 */
	public function get_address_string($id)
	{
		$address_string = '';
		
		$instance = $this->select_instance_by_id($id);
		if (empty($instance)) return $address_string;
		
		$path = $this->calculate_path_by_position($instance['position']);
		
		$parents = $this->db
							->where_in('id', $path)
							->get($this->table_mapper['master'])
							->result_array();
		$parents = array_column($parents, null, 'id');
		foreach ($path as $parent_id) {
			if (empty($parents[$parent_id])) {
				continue;
			}
			$address_string .= $parents[$parent_id]['name'] . ' ';
		}
		$address_string .= $instance['name'];
		
		return $address_string;
	}
	
}